import React,{Component} from 'react';
import { connect } from 'react-redux';
import { Card,Button,Input,Table,message,Form,Select,Modal,DatePicker,Space  } from 'antd';
import { ModalForm } from '@ant-design/pro-form';
import dayjs from 'dayjs';
import { PlusCircleOutlined,ExclamationCircleOutlined,SearchOutlined } from '@ant-design/icons';
import {reqUserList,reqAddUser,reqUpdateUser,reqDeleteUser,reqSearchUser,reqSearchStudentInfo} from '../../api';
import { saveStudentAction } from '../../redux/action_creators/user_action';
import {PAGE_SIZE} from '../../config';
import moment from 'moment';
const {Item} =Form;
const { Option } = Select;

@connect(
    state=>({userList:state.userList}),
    {
        saveStudentList:saveStudentAction
    }
)
 class Student extends Component {
    state={
        userList:[],//用户列表
        roleList:[],//角色列表
        isLoading:true, //table是否显示加载动画
        id:'',
        keyWord:'', //搜索关键词
        searchType:'username',//默认搜索方式按名称搜索
        isVisible:false,
        birthday:'',
        studentCourseList:[]
    }
    componentDidMount(){
        const {studentList } = this.props.userList;
        if(studentList.length>0){
            // console.log(studentList);
            this.setState({
                userList:studentList,
                isLoading:false,
            })
        }else{
            this.getUserList()
        }
 
    }
    // 获取用户列表
    getUserList = async () => {
        let result = await reqUserList()
        const { code,data,msg} = result
        // console.log(result);
       if(code === 200){
           if(data.length===0)  message.success(msg,1)
           this.setState({
            userList:data,
            isLoading:false,
        })
            //   把用户列表保存到redux中
              this.props.saveStudentList(data)
        }else{
            message.error(msg,1)      
        } 
    }
    // 用户弹窗设置确定
    handleAuthOk = async (values,id,type)=>{
        let result
        // console.log(values,type);
        if(type ==="add"){
            result = await reqAddUser(values)
            const { code,data,msg} = result
            console.log(data);
            if(code === 200){
                message.success('添加用户成功！',1)
                let userList = [...this.state.userList]
                userList.unshift(data[0])
                this.setState({userList})
                this.props.saveStudentList(userList)

            }else{
                message.error(msg,1)
            }
        }else{
            result = await reqUpdateUser({...values,id})
            const { code,data,msg} = result
            if(code === 200){
                message.success('修改用户成功！',1)
                let userList = [...this.state.userList]
                userList = userList.map((item)=> item.id === data[0].id ? data[0] : item);
                this.setState({userList})
                this.props.saveStudentList(userList)
            }else{
                message.error(msg,1)
            }
        }
    }
    // 删除用户信息
    getDelete = async (id) =>{
        let  result = await reqDeleteUser(id)
        console.log(result);
        const { code,msg} = result
        if(code === 200){
            message.success('删除用户成功！',1)
            let userList = [...this.state.userList]
            let userIndex;
            userList.forEach((item,index)=> {
                if(item.id === id) userIndex=index
            });
            userList.splice(userIndex,1)
            this.props.saveStudentList(userList)
            this.setState({userList})
        }else{
            message.error(msg,1)
        }
    }
    // 删除用户信息
    deleteUser =  (id) => {
        let{ getDelete } = this
        Modal.confirm({
            icon: <ExclamationCircleOutlined/>,
            title:'删除用户',
            content:'你确定要删除用户信息吗？',
            okText:'确定',
            cancelText:'取消',
            onOk(){
                getDelete(id)
            },
            onCancel() {
            console.log('取消');
            },
        });
    }
    // 根据搜索类型搜索
    searchProduct=  () => {
        const {keyWord} = this.state;
        const {studentList } = this.props.userList;
        if(keyWord.length>0){
            this.searchUserList()
        }else{
            this.setState({
                userList:studentList,
                isLoading:false,
            })
        }
    }
    
    // 获取用户列表
    searchUserList = async () => {
        const {searchType,keyWord} = this.state
        console.log(searchType,keyWord);
        let result = await reqSearchUser(searchType,keyWord)
        const { code,data,msg} = result
        console.log(result);
       if(code === 200){
            this.setState({
                userList:data,
                isLoading:false,
            })
              // 把用户列表保存到redux中
            //   this.props.saveProductList(data.list)
        }else if(code === 404){
            this.props.history.push(`/admin/error`)
        }else{
            message.error(msg,1)      
        } 
    }
    // 修改时间
    onChangeDate=(date, dateString) =>{
        this.setState({birthday:dateString});
        console.log(dateString);

    }
    showModel=(type,item)=>{
        const {username,password,phone,email,sex,id,birthday,userNum}=item
        return(
            <ModalForm
                title={type==="primary"?'添加学员':'修改学员'}
                width={'600px'}
                trigger={<Button type={type}>{type==="primary"?<PlusCircleOutlined/>:''}{type==="primary"?'添加学员':'修改'}</Button>}
                submitter={{
                searchConfig: {
                    submitText: '确认',
                    resetText: '取消',
                },
                }}
                onFinish={ (values) => {
                    if(type==="primary") this.handleAuthOk(values,'',"add")
                    else this.handleAuthOk(values,id,"update")
                    return true;
                }} >
                <Item label="姓名"
                    name="username"
                        initialValue={username || ''}
                    rules={[
                        {required: true,message: '姓名不能为空',},
                        {max: 8,message: '姓名必须小于等于8位',},
                        {min: 2,message: '姓名必须大于等于2位',},

                    ]}
                >
                    <Input placeholder="请输入姓名"  allowClear/>
                </Item>
                <Item label="学号"
                    name="userNum"
                        initialValue={userNum || ''}
                    rules={[
                        {required: true,message: '学号不能为空',},
                        {pattern: /^\w+$/,message: '学号只能由英文数字下划线组成',},
                        {max: 12,message: '学号必须小于等于12位',},
                        {min: 4,message: '学号必须大于等于4位',},

                    ]}
                >
                    <Input placeholder="请输入学号"  allowClear disabled={type==="primary"?false:true}/>
                </Item>
                <Item label="手机号"
                    name="phone"
                    initialValue={phone || ''}
                    rules={[
                        {required: true,message: '手机号不能为空',},
                        {pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,message: '手机号有误',},
                    ]}
                >
                    <Input placeholder="请输入手机号"  allowClear/>
                </Item>
                <Item label="生日"
                    name="birthday"
                    initialValue={birthday?moment(dayjs(birthday).format('YYYY-MM-DD'), 'YYYY-MM-DD'):'' }
                    rules={[
                        {required: true,message: '生日不能为空'}
                    ]}
                >
                    <DatePicker allowClear style={{width:"550px"}}  onChange={this.onChangeDate} placeholder="请选择日期"/>
                </Item>
                <Item label="邮箱"
                    name="email"
                    initialValue={email || ''}
                    rules={[
                        {required: true,message: '邮箱不能为空',},
                        {pattern: /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/,message: '邮箱有误！',},
                    ]}
                >
                    <Input placeholder="请输入邮箱"  allowClear/>
                </Item>
                <Item label="性别"
                    name="sex"
                        initialValue={sex ||'男'}
                    rules={[{required: true,message: '请选择性别',}]}
                >
                    <Select placeholder="请选择性别" >
                    <Option key={'1'} value={"男"}>男</Option>
                    <Option key={'0'} value={"女"}>女</Option>
                    </Select>
                </Item>
                {type==="primary"?<div className="pic">注：初始密码为：12345678</div>:'' }
            </ModalForm>
        )
    }
    // 展示弹窗
    showModelCourse=async(userId)=>{
        console.log(userId);
        let result = await reqSearchStudentInfo(userId)
        const { code,data,msg} = result
        console.log(result);
        if(code === 200){
        if(data.length===0)  message.success(msg,1)
            this.setState({
                studentCourseList:data,
                isVisible:true,
            })
        }else{
            message.error(msg,2)      
        } 
        
    }
    render(){
        const { userList,searchType,isVisible,studentCourseList } = this.state
          const columns = [
            {
              title: '姓名',
              dataIndex: 'username',
              key: 'id',
            },
            {
                title: '学号',
                dataIndex: 'userNum',
                key: 'id',
              },
            {
              title: '邮箱',
              dataIndex: 'email',
              key: 'id',
            },
            {
                title: '生日',
                dataIndex: 'birthday',
                key: 'id',
                render:time=>dayjs(time).format('YYYY年MM月DD日')
            },
            {
              title: '电话',
              dataIndex: 'phone',
              key: 'id',
            },
            {
                title: '注册时间',
                dataIndex: 'createTime',
                key: 'id',
                render:time=>dayjs(time).format('YYYY年MM月DD日  HH:mm:ss')
            },
            {
                title: '性别',
                dataIndex: 'sex',
                key: 'id',
            },
            {
                title: '操作',
                key: 'id',
                align:'center',
                render:(item)=>{
                    return(
                        <div>
                            <Button type="link" onClick={()=>{this.showModelCourse(item.id)}}>个人课程</Button>
                            {this.showModel("link",item)}
                            <Button type="link" onClick={()=>{this.deleteUser(item.id)}}>删除</Button>
                        </div>
                    )
                }
            },
          ];
          const columnCourse = [
            {
              title: '课程编号',
              dataIndex: 'courseNum',
              key: 'id',
            },
            {
                title: '课程名称',
                dataIndex: 'courseName',
                key: 'id',
              },
            {
              title: '讲师工号',
              dataIndex: 'teacherNum',
              key: 'id',
            },
            {
                title: '讲师名称',
                dataIndex: 'teacherName',
                key: 'id',
            },
            {
                title: '报名时间',
                dataIndex: 'createTime',
                key: 'id',
                render:time=>dayjs(time).format('YYYY年MM月DD日  HH:mm:ss')
            },
            {
                title: '状态',
                // dataIndex: 'status',
                key: 'id',
                align:'center',
                width:'20%',
                render:(item)=><span>{item.status=== 1 ? '已报名':(item.status=== 0 ? '申请退课中':'已退课')}</span>    
            },
            {
                title: '课程分数',
                dataIndex: 'mark',
                key: 'id',
            },
          ];

        return (
            <div>
                <Card
                    title={
                        <Space size="small">
                            <Select 
                                defaultValue={searchType} 
                                style={{ width: 120 }} 
                                onChange={(value)=>{this.setState({searchType:value})}}
                            >
                                <Option value="username">按姓名搜索</Option>
                                <Option value="userNum">按学号搜索</Option>
                            </Select>
                            <Input 
                            style={{ width: 210 }} 
                                placeholder="关键字" 
                                className="selectInput" 
                                allowClear
                                onChange={(event)=>{this.setState({keyWord:event.target.value})}}
                            />
                            <Button
                                type="primary"
                                onClick={this.searchProduct}
                            >
                                <SearchOutlined />搜索
                            </Button>
                        </Space>
                     } 
                     extra={
                        <div>
                            {this.showModel("primary","")}
                        </div>
                     }
                >
                    <Table 
                        dataSource={userList} 
                        columns={columns}
                        bordered
                        rowKey='id'
                        pagination={{
                            pageSize:PAGE_SIZE,
                        }}
                        loading={this.state.isLoading} 
                    />
                </Card>
                <Modal
                    title="已选课程"
                    visible={isVisible}
                    onOk={()=>this.setState({isVisible:false})}
                    onCancel={()=>this.setState({isVisible:false})}
                    footer={null}
                    maskClosable={false}
                    width={1200}
                    >
                     <Table 
                        dataSource={studentCourseList} 
                        columns={columnCourse}
                        bordered
                        rowKey='id'
                        pagination={{
                            pageSize:PAGE_SIZE,
                        }}
                        loading={this.state.isLoading} 
                    />
                    </Modal>
            </div>
        );
    }
}
export default Student;